package com.jnc.rest.core.config.mybatis;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.jnc.rest.constant.SysConstant;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @Author: jjn
 * @Date: 2019/12/13
 * @Description: base数据源配置
 */
@Configuration
@EnableTransactionManagement   //开启事务注解(配置方法上的注解@Transactional使用)
public class  BaseDataSourceConfig {


    // 指定该数据源对应的mapper接口目录，以便跟其他数据源隔离
    static final String PACKAGE = "com.jnc.rest.biz.**.mapper";
    static final String MAPPER_LOCATION = "classpath:mapper/*/*/*.xml";

    /**
     * 获取数据源datasource
     *
     * @return
     */
    @Bean(name = "baseDataSource")
    @ConfigurationProperties(prefix = "base.datasource")
    public DataSource baseDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 获取sqlSessionFactory工厂实例
     * @return
     * @throws Exception
     */
    @Bean(name = "baseSqlSessionFactory")
    public SqlSessionFactory baseSqlSessionFactory(@Qualifier("baseDataSource") DataSource baseDataSource) throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(baseDataSource);

        //配置分页插件
        PageHelper pageHelper = new PageHelper();
        Properties pro = new Properties();
        pro.setProperty("pageSizeZero", "true");//分页尺寸为0时查询所有纪录不再执行分页
        pro.setProperty("reasonable", "true");//页码<=0 查询第一页，页码>=总页数查询最后一页
        pro.setProperty("supportMethodsArguments", "true");//支持通过 Mapper 接口参数来传递分页参数
        pageHelper.setProperties(pro);
        //添加插件
        factory.setPlugins(new Interceptor[]{pageHelper});

        //添加xml目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factory.setMapperLocations(resolver.getResources(BaseDataSourceConfig.MAPPER_LOCATION));
        return factory.getObject();
    }

    /**
     * 事务管理器
     * @return
     */
    @Bean(name = SysConstant.TX_BASE_NAME)
    public DataSourceTransactionManager baseTransactionManager(){
        return new DataSourceTransactionManager(baseDataSource());
    }

}
